﻿using Abp.Authorization;
using Abp.Linq.Expressions;
using Abp.UI;
using Basefr.App;
using Microsoft.AspNetCore.Mvc;
using Paas.App.Interface.MetaPages;
using Paas.App.Interface.MetaPages.Dtos;
using Paas.App.Interface.MetaPages.Messages;
using Paas.Core;
using Paas.Core.Const.Enums;
using Paas.Core.Meta.Entities;
using Paas.Core.MetaPages.Entities;
using Paas.Core.MetaViews.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Paas.App.MetaPages
{
    [Route("metaPages-metaPage")]

    [AbpAuthorize()]
    public class MetaPageAppService: AppService, IMetaPageAppService
    {
        private readonly IMainRepository<MetaPage, Guid> _metaPageRepo;
        private readonly IMainRepository<MetaObject,Guid> _metaObjectRepo;
        private readonly IMainRepository<MetaView, Guid> _metaViewRepo;


        public MetaPageAppService(IMainRepository<MetaPage, Guid> metaPageRepo,IMainRepository<MetaObject,Guid> metaObjectRepo, IMainRepository<MetaView, Guid> metaViewRepo)
        {
            _metaPageRepo = metaPageRepo;
            _metaObjectRepo = metaObjectRepo;
            _metaViewRepo = metaViewRepo;
        }

        #region 增改
        [HttpPost(nameof(SaveMetaPage))]
        public async Task<SaveMetaPageOutput> SaveMetaPage(SaveMetaPageInput input)
        {
            if (input == null) throw new UserFriendlyException("保存信息失败：input为空！");
            var entity = ObjectMapper.Map<MetaPage>(input.Item);

            //获取包含的视图，用,隔开
            var viewIds= string.Join(",", input.Item.MetaViewIdList); 
            entity.MetaViewIds= viewIds;

            if (input.Item?.Id != null && input.Item?.Id != Guid.Empty)
            {
                //var uData = await _metaPageRepo.GetAsync(input.Item.Id);
                //if (uData == null) throw new UserFriendlyException("未找到需要更新的页面配置！");

                #region 需要更新的字段
                //uData.Label = input.Item.Label;
                //uData.Description = input.Item.Description;
                //uData.MetaGroup= input.Item.MetaGroup;
                #endregion

                await _metaPageRepo.UpdateAsync(entity); ;
                return new SaveMetaPageOutput();
            }

            //设置一些默认的值
            //entity.CurrentStatus ??= MetaStatus.New;
            //entity.IsPublic = true;

            await _metaPageRepo.InsertAsync(entity);

            return new SaveMetaPageOutput();
        }
        #endregion

        #region 查
        [HttpPost(nameof(SearchMetaPage))]
        public async Task<SearchMetaPageOutput> SearchMetaPage(SearchMetaPageInput input)
        {
            Expression<Func<MetaPage, bool>> predicate = p => true;
            if (!string.IsNullOrWhiteSpace(input.Name))
            {
                predicate = predicate.And(p => p.Name.Contains(input.Name.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(input.Label))
            {
                predicate = predicate.And(p => p.Label.Contains(input.Label.Trim()));
            }
            if (input.ApplicationId != null && input.ApplicationId != 0)
            {
                predicate = predicate.And(p => p.ApplicationId == input.ApplicationId);
            }

            var result = await _metaPageRepo.GetAllListAsync(predicate);
            var res = result.OrderByDescending(p => p.SortNum).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            var totalCount = result.Count();
            var resultItems = ObjectMapper.Map<List<MetaPageDto>>(res);
            //获取包含的视图名称
            if (totalCount > 0)
            {
                foreach (var item in resultItems)
                {
                    var metaViewIds = item.MetaViewIds?.Split(',');
                    List<string> list = new List<string>();
                    foreach (var metaViewId in metaViewIds)
                    {
                        var metaViewLabe = _metaViewRepo.FirstOrDefault(p => p.Id.ToString()== metaViewId);
                        list.Add(metaViewLabe?.Label);
                    }
                    // 使用string.Join方法将列表元素用逗号分隔并转换为字符串
                    string metaViewLabes = string.Join(",", list);
                    item.MetaViews= metaViewLabes;
                    item.MetaViewIdList=metaViewIds.ToList();
                }
            }
            return new SearchMetaPageOutput { Items = resultItems, TotalCount = totalCount };
        }

        /// <summary>
        /// 根据id查询单条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost(nameof(SearchSingleMetaPage))]
        public async Task<SearchSingleMetaPageOutput> SearchSingleMetaPage(SearchSingleMetaPageInput input)
        {

            var result = await _metaPageRepo.FirstOrDefaultAsync(input.Id);
            var resultItem = ObjectMapper.Map<MetaPageDto>(result);

            return new SearchSingleMetaPageOutput() { Item=resultItem };
        }

        #endregion

        #region 删
        [HttpPost(nameof(DeleteMetaPage))]
        public async Task<DeleteMetaPageOutput> DeleteMetaPage(DeleteMetaPageInput input)
        {
            //await _metaPageRepo.
            await _metaPageRepo.DeleteAsync(input.Id);
            return new DeleteMetaPageOutput();
        }
        #endregion
    }
}
